package com.mai4j.maiadmin.support.security.aop.annotation;


import com.mai4j.maiadmin.support.security.SecurityUtils;
import com.mai4j.maiadmin.support.security.aop.AuthorizingAnnotationHandler;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.AccessDeniedException;

import java.lang.annotation.Annotation;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
public class PermissionsAnnotationHandler extends AuthorizingAnnotationHandler {

    public PermissionsAnnotationHandler() {
        super(RequiresPermissions.class);
    }

    @Override
    public void assertAuthorized(Annotation a, MethodInvocation mi) throws AccessDeniedException {
        if (a instanceof RequiresPermissions) {
            RequiresPermissions permissions = (RequiresPermissions) a;
            String[] value = permissions.value();
            switch (permissions.logical()) {
                case OR:
                    if (!SecurityUtils.Helper.hasAnyAuthority(value)) {
                        throw new AccessDeniedException("Access is denied");
                    }
                    break;
                case AND:
                    if (!SecurityUtils.Helper.hasAllAuthority(value)) {
                        throw new AccessDeniedException("Access is denied");
                    }
                    break;
            }
        }
    }
}
